package com.tcoding.client.controller.test.controlsfx;

import com.jfoenix.controls.JFXTooltip;
import com.tcoding.client.event.CustomerEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import org.apache.poi.ss.formula.functions.T;
import org.controlsfx.control.GridCell;

import java.util.HashMap;

public class CustomerImageGridCell extends GridCell<ImageView> {
    private final ImageView imageView;
    private final boolean preserveImageProperties;
    private final EventHandler eventHandler;
    public CustomerImageGridCell() {
        this(true,null);
    }

    public CustomerImageGridCell(boolean preserveImageProperties, EventHandler<CustomerEvent<T>> handler) {
        this.getStyleClass().add("image-grid-cell");
        this.preserveImageProperties = preserveImageProperties;
        this.imageView = new ImageView();
        this.imageView.fitHeightProperty().bind(this.heightProperty().subtract(20));
        this.imageView.fitWidthProperty().bind(this.widthProperty().subtract(20));
        this.eventHandler = handler;
    }

    @Override
    protected void updateItem(ImageView item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            this.setGraphic((Node)null);
        } else {
            if (this.preserveImageProperties) {
                this.imageView.setPreserveRatio(item.isPreserveRatio());
                this.imageView.setSmooth(item.isSmooth());
            }
            this.imageView.setImage(item.getImage());
            Object userData = item.getUserData();

            VBox v = new VBox();
            v.getChildren().add(this.imageView);
            v.getChildren().add(new Label(userData.toString()));
            v.setAlignment(Pos.CENTER);
            v.setSpacing(5);
            this.setGraphic(v);
            JFXTooltip.install(v,new JFXTooltip(userData.toString()));
            this.setCursor(Cursor.HAND);
            this.setOnMouseClicked(e-> eventHandler.handle(new CustomerEvent<>(e, new HashMap<String, Object>(4) {{
                put("data", userData);
            }})));
        }

    }
}
